CREATE OR REPLACE FUNCTION "pipeline"."sys_func_pivot_table_output_col"("table_name" varchar, "rowc" varchar, "cols" _varchar, "colsize" int4, "statistic" varchar)
  RETURNS "pg_catalog"."varchar" AS $BODY$
declare
    sql_1 varchar;
    sql_2 varchar;
    sql_3 varchar;
    sql_4 varchar;
		groupsql_1 varchar;
		col varchar;
		colc varchar;
    meth varchar;
    meth_name varchar;
    stcs RECORD;
		num integer;
		col_length integer;
		row_length integer;
		sql_part_1 varchar;
		cols_str varchar;
		col_limit integer;
		col_limit_p integer;

begin
    cols_str = array_to_string(cols,',');
		groupsql_1 = ' from '||table_name||' group by '||cols_str||' order by '||cols_str;
		sql_3 = '';
		row_length = array_length(string_to_array(rowc,','), 1)+1;
		col_length = array_length(cols, 1);

		if colsize<2 then
			return '限制长度不能小于2';
		end if;
		if colsize>1600 then
			return '最大限制长度为1600';
		end if;
		if row_length>colsize then
			return '限制长度至少比行标签个数多一个';
		end if;

		col_limit = colsize-row_length+1;

		for stcs in (select json_array_elements(statistic::json)->>'col' col,json_array_elements(statistic::json)->>'method' meth,json_array_elements(statistic::json)->>'name' name ) loop
			col = stcs.col;
			meth = stcs.meth;
			meth_name = stcs.name;
			continue when col='' or meth='';
			if meth_name = '' or meth_name is null then
				meth_name = meth;
			end if;

			if col_length=1 then
				colc = cols[1];
				sql_1 = colc||'||''_'||col||'_'||meth_name||'''';
			else
				for num in 1..col_length loop
					colc = cols[num];
					if num=1 then
						sql_part_1 = colc||'||''_''';
					else
						sql_part_1 = sql_part_1||'||'||colc||'||''_''';
					end if;
				end loop;
				sql_1 = sql_part_1||'||'''||col||'_'||meth_name||'''';
			end if;
			sql_2 = 'select string_agg(new_col,'','')from(select '||sql_1||' new_col '||groupsql_1||' limit '||col_limit||') a';
			execute sql_2 into sql_4;
			if  sql_3 = '' then
				sql_3 = sql_4;
			else
				sql_3 = sql_3||','||sql_4;
			end if;
			col_limit_p = array_length(string_to_array(sql_4,','), 1);
			col_limit = col_limit-col_limit_p;
			exit when col_limit =0;
		end loop;

		return rowc||','||sql_3||',_record_id_';

end
$BODY$
  LANGUAGE 'plpgsql' VOLATILE COST 100
;